<?php 
/*************************************************************************************
 * commondb.php
 * -----------
 * phpGMapTrips 
 * 
 * This php application allows you to easily record your travel destinations 
 * and display them with Google maps.
 * 
 * Author: Stephane Coste (lescoste@gmail.com)
 * Copyright: (c) 2006 Stephane Coste (http://lescoste.net/)
 * Release Version: 0.1
 * CVS Revision Version: $Revision: 1.3 $
 * Date Started: 2006/02/19
 * Last Modified: $Date: 2007/03/14 14:32:43 $
 *
 *************************************************************************************
 *
 *     This file is part of phpGMapTrips.
 *
 *   phpGMapTrips is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   phpGMapTrips is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with phpGMapTrips; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 ************************************************************************************/
?>
<?php 
/************
* Public functions 
************/


// @return optional trips array : key = trip, value = points array : key = point name, value = point attributes array
function getTripGroups($atripname) {
	global $optdb_triparray;
	$tripname = $atripname;
	loadOptData();
	return $optdb_triparray["lesc_groups"];
}

// @return points array : key = point name, value = point attributes array
function getGroupPoints($atripname) {
	global $db_pointarray, $tripname;
	$db_pointarray = array();
	$tripname = $atripname;
	// it may be a group
	$grouparray = getGroups();
	$tmpdb_pointarray = array();
	if (!empty($grouparray)) {
		foreach ($grouparray[$atripname] as $gtripname) {
			$tmppointarray = getTripPoints($gtripname);
			foreach ($tmppointarray as $point) {
				array_push($tmpdb_pointarray, $point);
			}
		}
	}
	$db_pointarray = $tmpdb_pointarray;
	return $db_pointarray;
}

// @return optional trips array : key = trip, value = points array : key = point sequence number, value = point attributes array
function getTripPointsOrder($atripname) {
	global $db_opttripseqarray, $tripname;
	$tripname = $atripname;
	loadOptData();
	return $db_opttripseqarray;
}

// @return optional trips array : key = trip, value = points array : key = point name, value = point attributes array
function getTripOptionalData($atripname) {
	global $optdb_triparray;
	$tripname = $atripname;
	loadOptData();
	return $optdb_triparray;
}

// find a new name that starts with name (adds a number at the end)
function getUniquePointName($name) {
	global $pointsNames;
	return getUniqueName($name, $pointsNames);
}

// record a new trip points order
function saveTripPointsOrder($fpw, $hasBeenSaved, $atripname, $pointorder, $atripgroups) {
	global $editedTrip, $tripname;
	$tripname = $atripname;
	$editedTrip["tripname"] = $atripname;
	$editedTrip["tripgroups"] = $atripgroups;
	$editedTrip["pointorder"] = $pointorder;
	$editedTrip["hasBeenSaved"] = $hasBeenSaved;
	$editedTrip["fpw"] = $fpw;
	parseAndCopyTripData();
	return $editedTrip["hasBeenSaved"];
}

/************
* Private functions 
************/
function loadOptData() {
	global $isOptParsed, $db_opttripseqarray, $optdb_triparray;
	if(!$isOptParsed) {
		$db_opttripseqarray = array();
		$optdb_triparray = array();
		parseTripOptionalData();
		$isOptParsed = true;
	}
}
function parseTripsData() {
	global $f_files;
	parseXmlFile($f_files, "startElement", "endElementTrip");
}
function parsePointsData() {
	global $f_files;
	parseXmlFile($f_files, "startElement", "endElementPoint");
}
function parseAndCopyPointData() {
	global $f_files;
	parseXmlFile($f_files, "startElement", "endElementCopyPoint");
}

function parseTripOptionalData() {
	global $f_trips;
	parseXmlFile($f_trips, "startElement", "endElementOptData");
}

function parseAndCopyTripData() {
	global $f_trips;
	parseXmlFile($f_trips, "startElement", "endElementCopyTrip");
}

function parseGroupData() {
	global $f_trips;
	parseXmlFile($f_trips, "startElementGroup", "endElementGroup");
}
function parseXmlFile($fileName, $startElementFunctionName, $endElementFunctionName) {
	global $f_files;

	$xml_parser = xml_parser_create("");
	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
	xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');

	xml_set_element_handler($xml_parser, $startElementFunctionName, $endElementFunctionName);
	xml_set_character_data_handler($xml_parser, "characterData");

	if ($fp = @fopen($fileName, "r")) {
		while ($data = fread($fp, 4096)) {
			$data = ereg_replace('&', '&amp;', $data);
			if (!xml_parse($xml_parser, $data, feof($fp))) {
				die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
			}
		}
	}
	xml_parser_free($xml_parser);
}


/**************************
fonctions de parsing du fichier xml
**************************/

function startElement($parser, $name, $attrs) {
	global $tb, $ph, $phs, $phindex, $currentMoreInfo, $ct;
	switch($name) {
		case 'TRIP':
			$ct['name'] = $attrs['NAME'];
			$ct['url'] = $attrs['URL'];
			$ct['groups'] = $attrs['GROUPS'];
			break;
		case 'POINT':
			$tb['name'] = $attrs['NAME'];
			$tb['title'] = $attrs['NAME'];
			$tb['lat'] = $attrs['LAT'];
			$tb['long'] = $attrs['LONG'];
			$tb['url'] = $attrs['URL'];
			$tb['trips'] = $attrs['TRIPS'];
			$tb['seq'] = $attrs['SEQ'];
			break;
		case 'PHOTO':
			$ph['url'] = $attrs['URL'];
			$phs[$phindex++]= $ph;
			$ph = array();
			break;
		case 'MOREINFO':
			$currentMoreInfo = $attrs['NAME'];
			break;
		}
	}

function endElementTrip($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'POINT':
			addTrip($tb, $phs, $ct);
			$tb = array();
			$phs = array();
			$phindex = 0;
			break;
		case 'MOREINFO':
			$tb[$currentMoreInfo] = $xmltagvalue;
			$xmltagvalue = "";
			break;
	}
}

function endElementPoint($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct, $findlatest, $loadAllNames;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'POINT':
			if ($loadAllNames) {
				addPointName($tb, $phs, $ct);
			} else if ($findlatest) {
				addLatestPoint($tb, $phs, $ct);
			} else {
				addPoint($tb, $phs, $ct);
			}
			$tb = array();
			$phs = array();
			$phindex = 0;
			break;
		case 'MOREINFO':
			$tb[$currentMoreInfo] = $xmltagvalue;
			$xmltagvalue = "";
			break;
	}
}
function endElementCopyPoint($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct, $findlatest;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'POINT':
			copyPoint($tb, $phs, $ct);
			$tb = array();
			$phs = array();
			$phindex = 0;
			break;
		case 'MOREINFO':
			$tb[$currentMoreInfo] = $xmltagvalue;
			$xmltagvalue = "";
			break;
	}
}


// Parsing trip optional data
function endElementOptData($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'TRIP':
			$ct = array();
			break;
		case 'POINT':
			addOrderPoint($tb, $phs, $ct);
			$tb = array();
			$phs = array();
			$phindex = 0;
			break;
		case 'MOREINFO':
			$tb[$currentMoreInfo] = $xmltagvalue;
			$xmltagvalue = "";
			break;
	}
}
function endElementCopyTrip($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'TRIP':
			copyTrip($tb, $phs, $ct);
			$ct = array();
			break;
		case 'POINT':
			addOrderPointForCopyTrip($tb, $phs, $ct);
			$tb = array();
			$phs = array();
			$phindex = 0;
			break;
		case 'MOREINFO':
			$tb[$currentMoreInfo] = $xmltagvalue;
			$xmltagvalue = "";
			break;
	}
}

// Parsing trip optional data
function startElementGroup($parser, $name, $attrs) {
	global $tb, $ph, $phs, $phindex, $currentMoreInfo, $ct;
	switch($name) {
		case 'TRIP':
			$ct['name'] = $attrs['NAME'];
			$ct['url'] = $attrs['URL'];
			$ct['groups'] = $attrs['GROUPS'];
			addGroup($ct);
			break;
		}
	}

function endElementGroup($parser, $name) {
	global $tb, $ph, $phindex, $phs, $currentMoreInfo, $xmltagvalue, $ct;
	$xmltagvalue = trim($xmltagvalue);
	switch($name) {
		case 'TRIP':
			$ct = array();
			break;
	}
}


function characterData($parser, $data) {
	global $xmltagvalue;
	$xmltagvalue .= $data;
}



function addGroup($ct) {
	global $db_grouparray;
	$gg= trim($ct["groups"]); 
	if(!empty($gg)) {
		$groupnames = split(";", $ct['groups']);
		// loop on all points trips
		foreach($groupnames as $groupname) {
			$groupname = trim($groupname);
			$trips = $db_grouparray[$groupname];
			if (empty($trips)) {
				$trips = array();
			}
			array_push($trips, $ct['name']);
			$db_grouparray[$groupname] = $trips;
		}
	}
}

function addTrip($tb, $phs, $ct) {
	global $db_triparray;
	$tagnames = split(";", $tb['trips']);
	// loop on all points trips
	foreach($tagnames as $tagname) {
		$tagname = trim($tagname);
		$db_triparray[$tagname] = $db_triparray[$tagname] + 1;
	}
}

function addOrderPoint($tb, $phs, $ct) {
	global $tripname, $db_opttripseqarray, $optdb_triparray;
	$atripname = $ct["name"];
	//		echo "<!-- $atripname -->";
	if ($atripname == $tripname) {
		// get previous seq array for trip
		$tripSeq = $db_opttripseqarray[$tripname]; //optional trips array : key = trip, value = points array : key = point sequence number, value = point attributes array
		if (empty($tripSeq)) {
			$tripSeq = array();
		}
		// add new point
		$tripSeq[$tb["seq"]] = $tb;
		// store new array
		$db_opttripseqarray[$tripname] = $tripSeq;


		$tripPoints = $optdb_triparray[$tripname];
		if (empty($tripPoints)) {
			$tripPoints = array();
		}
		// add new point
		$tripPoints[$tb["name"]] = $tb;
		// store new array
		$optdb_triparray[$tripname] = $tripPoints;
		$optdb_triparray["lesc_groups"] = $ct["groups"];
	}
} 

function addPoint($tb, $phs, $ct) {
	global $search, $tripname, $db_pointarray, $alltrips;

	// check to see if it is needed to keep this point
	if (isFound($tb["name"], $search)) {
		$tripfound = true;
	}

	if (!$tripfound) {
		// loop on all points trips
		$tagnames = split(";", $tb['trips']);
		foreach($tagnames as $tagname) {
			$tagname = trim($tagname);
			if ($tripname == $tagname || ($tripname == "All" && !array_key_exists($tagname, $alltrips)) ) {
				$tripfound = true;
                                $alltrips[$tagname] = true;
				break;
			}
		}
	}
	if (!$tripfound) {
		return;
	}

	// store photos
	$tb["photos"] = $phs;

	// store an array of points
	$db_pointarray[$tb["name"]] = $tb;
}

function addPointName($tb, $phs, $ct) {
	global $pointsNames, $rootname;
	// store an array of points names
	$result = false;
	$pos = @strpos($tb["name"], $rootname);
	if ($pos===false) {
	} else {
		if ($pos == 0) {
			$pointsNames[$tb["name"]] = $tb["name"];
		}
	}
}

function addLatestPoint($tb, $phs, $ct) {
	global $db_datearray;

	// store photos
	$tb["photos"] = $phs;

	//sort by date; convert 19-07-2006 to 20060719
	$pdate = $tb["date"];
	if (!empty($pdate)) {
		$re = "/(\d{2})-(\d{2})-(\d{4})/";
		preg_match ( $re, $pdate, &$matchArray);
		$pdate = $matchArray[3].$matchArray[2].$matchArray[1];
		$db_datearray[$pdate] = $tb;

		krsort($db_datearray);
		if (count($db_datearray) > 10 ) {
			$db_datearray = array_slice($db_datearray, 0, 10);
		}
	}
}

function copyPoint($tb, $phs, $ct) {
	global $editedPoint, $lang_place, $lang_place_renamed, $lang_place_updated, $lang_place_deleted;

	// if the point name has been changed
	if ($tb["name"] == $editedPoint["oldname"]) {
		// if the new name is not empty
		if (!empty($editedPoint["newname"])) {
			// if the new name is different from the old one
			if ($editedPoint["newname"] != $editedPoint["oldname"]) {
				$editedPoint["newname"] = getUniquePointName($editedPoint["newname"]);
				echo '<br/>'.$lang_place.' '.$editedPoint["oldname"].' '.$lang_place_renamed.' '.$editedPoint["newname"].'.';
			} else {
				echo '<br/>'.$lang_place.' '.$editedPoint["oldname"].' '.$lang_place_updated.'.';
			}
			fwrite($editedPoint["fpw"], printPoint($editedPoint["newname"], $editedPoint["lat"], $editedPoint["lng"], $editedPoint["url"], $editedPoint["photo"], $editedPoint["tags"], $editedPoint["moreinfo"]));
			$editedPoint["hasBeenSaved"] = true;
		} else {
			echo '<br/>'.$lang_place.' '.$editedPoint["oldname"].' '.$lang_place_deleted.'.';
			$editedPoint["hasBeenSaved"] = true;
		}
	} else {
		fwrite($editedPoint["fpw"], printPoint($tb["name"], $tb["lat"],$tb["long"],$tb["url"],$phs[0]["url"], $tb["trips"], $tb));
	}
}


function addOrderPointForCopyTrip($tb, $phs, $ct) {
	global $tripname, $db_opttripseqarray, $optdb_triparray;
	$atripname = $ct["name"];
	// get previous seq array for trip
	$tripSeq = $db_opttripseqarray[$atripname]; //optional trips array : key = trip, value = points array : key = point sequence number, value = point attributes array
	if (empty($tripSeq)) {
		$tripSeq = array();
	}
	// add new point
	$tripSeq[$tb["seq"]] = $tb;
	// store new array
	$db_opttripseqarray[$atripname] = $tripSeq;
} 

function copyTrip($tb, $phs, $ct) {
	global $editedTrip, $db_opttripseqarray, $lang_place, $lang_place_updated;
	// we found the trip to update
	if ($ct["name"] == $editedTrip["tripname"]) {
		echo '<br/>'.$lang_place.' '.$editedTrip["tripname"].' '.$lang_place_updated.'.';
		fwrite($editedTrip["fpw"], printTrip($ct["name"], $editedTrip["tripgroups"], $db_opttripseqarray[$ct["name"]], $editedTrip["pointorder"]));
		$editedTrip["hasBeenSaved"] = true;
	} else {
		// just copy this trip
		fwrite($editedTrip["fpw"], printTrip($ct["name"], $ct["groups"], $db_opttripseqarray[$ct["name"]], array()));
	}
	$db_opttripseqarray = array();
}
?>
